package com.gcb.framework.utils;

import com.gcb.common.constant.Constants;
import com.gcb.common.constant.HttpStatus;
import com.gcb.common.core.domain.TreeSelect;
import com.gcb.common.core.domain.entity.SysRole;
import com.gcb.common.exception.ServiceException;
import com.gcb.common.utils.StringUtils;
import com.gcb.framework.model.AppLoginUser;
import com.gcb.framework.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.PatternMatchUtils;

import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 安全服务工具类
 *
 * @author ruoyi
 */
public class SecurityUtils {


    /**
     * 递归获取当前部门树所有部门id
     * @param trees 部门树
     * @param deptIds 空部门id集合
     * @return deptIds 部门id集合
     */
    public static List<Long> getDeptIds(List<TreeSelect> trees, List<Long> deptIds) {
        for (TreeSelect tree : trees) {
            deptIds.add(tree.getId());
            if (tree.getChildren() != null && !tree.getChildren().isEmpty()) {
                getDeptIds(tree.getChildren(), deptIds);
            }
        }
        return deptIds;
    }


    /**
     * 判断是否为总部员工
     * @return boolean
     */
    public static boolean isAdminDept() {
        Long operateId = getLoginUser().getOperateId();
        return operateId != null && 100L == operateId;
    }

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId() {
        try {
            return getLoginUser().getDeptId();
        } catch (Exception e) {
            throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }
    /**
     * 获取app用户默认登入账号
     **/
    public static String getDefaultAppUserPassword(String mobile) {
        try {
            return encryptPassword(mobile.substring(mobile.length() - 6));
        } catch (Exception e) {
            throw new ServiceException("加密用户默认密码异常", HttpStatus.WARN);
        }
    }
    /**
     * 验证用户手机号
     **/
    public static void verifyMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            throw new ServiceException("手机号不可为空");
        } else if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(mobile).matches()) {
            throw new ServiceException("请输入正确手机号");
        }
    }

    /**
     * 手机号脱敏
     **/
    public static String desMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            throw new ServiceException("手机号不可为空");
        }
        return mobile.replaceAll("(\\w{3})\\w*(\\w{4})", "$1*****$2");
    }



    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static UserDetails getUserDetails() {
        try {
            return (UserDetails)getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }
    /**
     * 获取app用户
     **/
    public static AppLoginUser getAppLoginUser() {
        try {
            return (AppLoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码（新方法移动到PassworUtils里面）
     *
     * @param password 密码
     * @return 加密字符串
     */
    @Deprecated
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同（新方法移动到PassworUtils里面）
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    @Deprecated
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        LoginUser loginUser = getLoginUser();
        return userId != null && 1L == userId;
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(String permission) {
        return hasPermi(getLoginUser().getPermissions(), permission);
    }

    /**
     * 判断是否包含权限
     *
     * @param authorities 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(Collection<String> authorities, String permission) {
        return authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> Constants.ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(x, permission));
    }

    /**
     * 验证用户是否拥有某个角色
     *
     * @param role 角色标识
     * @return 用户是否具备某角色
     */
    public static boolean hasRole(String role) {
        List<SysRole> roleList = getLoginUser().getUser().getRoles();
        Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        return hasRole(roles, role);
    }

    /**
     * 判断是否包含角色
     *
     * @param roles 角色列表
     * @param role  角色
     * @return 用户是否具备某角色权限
     */
    public static boolean hasRole(Collection<String> roles, String role) {
        return roles.stream().filter(StringUtils::hasText)
                .anyMatch(x -> Constants.SUPER_ADMIN.contains(x) || PatternMatchUtils.simpleMatch(x, role));
    }

}
